<template>
<div>
  <div v-loading="loading">
    <div class="app-container" style="background: seashell;margin: 0 auto;">
      <template v-if="seeFlag != '0' && reload.status == '1'">
        <el-descriptions class="margin-top" title="我的成绩" :column="2" border>
          <el-descriptions-item label="测试">{{bank.name}}</el-descriptions-item>
          <el-descriptions-item label="题目总数">{{bank.total}}</el-descriptions-item>
          <el-descriptions-item label="测试日期">{{reload.createTime}}</el-descriptions-item>
<!--          <el-descriptions-item label="完成日期">{{bank.endTime}}</el-descriptions-item>-->
          <el-descriptions-item label="正确数">{{reload.right}}</el-descriptions-item>
          <el-descriptions-item label="状态">已结束</el-descriptions-item>
          <el-descriptions-item label="得分">{{reload.score}}</el-descriptions-item>
        </el-descriptions>
      </template>
    </div>
    <!-- ======================= 答题区 ============================== -->
    <div v-if="reload.status == '1'">
      <template>
        <div class="my_tag_title">
          <span class="my_span">测试中...</span>&nbsp;&nbsp;&nbsp;
          <span>{{page.doCount}}/{{questionList.length}}</span>
        </div>
        <div class="my_space_title" style="background: seashell">
          <b class="ml10">问题</b>
        </div>
        <div class="my_tag_title">
          <span class="my_span">{{question.content}}</span>
        </div>
        <div class="my_space_title" style="background: seashell">
          <b class="ml10">选项（{{question.type == '0'?'单选':'多选'}}）</b>
        </div>
        <div class="my_question_title">
          <el-form label-width="0px" size="mini">
            <el-form-item style="margin-bottom: 0" v-for="option in question.optionList">
              <template>
                <template v-if="question.type=='0'">
                  <el-radio class="my_span" @change="$forceUpdate()" v-model="answers[question.id]" :label="option.k">{{option.k}}.{{option.v}}</el-radio>
                </template>
                <template v-else>
                  <el-checkbox-group class="my_span" v-model="answers[question.id]" @change="$forceUpdate()">
                    <el-checkbox :label="option.k">{{option.k}}.{{option.v}}</el-checkbox>
                  </el-checkbox-group>
                </template>
              </template>
            </el-form-item>
          </el-form>
        </div>
      </template>
    </div>
    <!-- ========================= 查看已作答 ============================ -->
    <div v-else>
      <template>
        <div class="my_tag_title">
          <span class="my_span">我的作答</span>&nbsp;&nbsp;&nbsp;
          <span>{{page.doCount}}/{{questionList.length}}</span>
        </div>
        <div class="my_space_title" style="background: seashell;padding-left: 10px">
          <b>问题</b>
        </div>
        <div class="my_tag_title">
          <span class="my_span">{{question.content}}</span>
        </div>
        <div class="my_space_title" style="background: seashell;padding-left: 10px">
          <b>选项（{{question.type=='0'?'单选':'多选'}}）</b>
          <el-tag v-if="questionAnswers[question.id]" type="success"><i class="el-icon-circle-check"/></el-tag>
          <el-tag v-else type="danger"><i class="el-icon-circle-close"/></el-tag>
        </div>
        <div class="my_question_title">
          <el-form label-width="0px" size="mini">
            <el-form-item style="margin-bottom: 0" v-for="option in question.optionList">
              <template>
                <template>
                  <span>{{option.k}}.{{option.v}}</span>
                </template>
              </template>
            </el-form-item>
            <el-form-item style="margin-top: 10px">
              <el-descriptions :column="1" :colon="false">
                <el-descriptions-item>
                </el-descriptions-item>
                <el-descriptions-item label="正确答案">
                  <el-link :underline="false" type="success">
                    <span v-for="q in question.answerList">{{q}}&nbsp;</span>
                  </el-link>
                </el-descriptions-item>
                <el-descriptions-item label="我的答案">
                  <el-link :underline="false" :type="questionAnswers[question.id] ? 'success' : 'danger'">
                    <span v-for="q in answers[question.id]">{{q}}&nbsp;</span>
                  </el-link>
                </el-descriptions-item>
              </el-descriptions>
            </el-form-item>
          </el-form>
        </div>
      </template>
    </div>
    <!-- ========================= 翻页 ============================ -->
    <div>
      <center style="margin-top: 20px">
        <el-button-group>
          <el-button v-if="page.doCount!='1'" icon="el-icon-arrow-left" size="mini" @click="selectQuestion(page.previous)">上一页</el-button>
          <el-button v-if="page.doCount!=questionList.length" type="primary" size="mini" @click="selectQuestion(page.next)">下一页<i class="el-icon-arrow-right el-icon--right"></i></el-button>
          <el-button v-if="page.doCount==questionList.length && reload.status == '1'" icon="el-icon-s-promotion" type="success" @click="submit" size="mini">交   卷</el-button>
        </el-button-group>
        <br>
        <el-button-group v-if="reload.status == '1'" style="width: 1000px;margin-top: 10px;">
          <el-button v-for="(item,index) in questionList" style="width: 55px;margin-top: 5px;margin-left: 3px" size="mini" @click="selectQuestion(index)"
                     :type="answers[item] != null && (answers[item] != '' && answers[item] != []) ? 'primary' :''">{{index+1}}</el-button>
        </el-button-group>
        <el-button-group v-else style="width: 1500px;margin-top: 10px;">
          <el-button v-for="(item,index) in questionList" style="width: 60px" size="mini" @click="selectQuestion(index)" :type="questionAnswers[item] ? 'success' :'danger'">{{index+1}}</el-button>
        </el-button-group>
      </center>
    </div>
    <span v-if="this.reload.status == '1'" class="text-red text-size-12">注：已做答案5秒自动保存一次，24小时内有效</span>
  </div>
</div>
</template>
<script>
import {getQuestion} from "@/api/ex/question";
import {question_apply, save_answers,get_answers} from "@/api/ex/question_bank";
import {updateEx_study_reload,getEx_study_reload} from "@/api/ex/ex_study_reload";
import {isNotEmpty} from "@/utils/zzDouUtils/ObjUtil";
import {parseTime} from "@/utils/ruoyi";

export default {
  name: "Test_bank",
  data() {
    return {
      loading:false,
      bankId:'',
      seeFlag:null,
      bank:{},
      reload:{},
      open:false,
      title:'',
      collapseActive:['1','2','3'],
      questionList:[],
      question:{},
      answers:{},
      questionAnswers:{},
      page:{
        doCount:1,
        index:'',//
        next:'',//下一页
        previous:'',//上一页
      },
      timer:null,
      saveCount:0,
    };
  },
 created() {
    this.bankId = this.$route.params && this.$route.params.testBankId;
    this.seeFlag = this.$route.params && this.$route.params.seeFlag;
    this.applyBank();
  },
  methods: {
    async applyBank(){
      this.loading = true;
      let response;
      if (this.seeFlag == '1'){
        //查询答题记录
        response = await getEx_study_reload(this.bankId);
      }else{
        response = await question_apply();
      }
      if (this.seeFlag == '1'){
        //this.bank = response.data;
        this.reload = response.data;
        this.questionList = response.data.questionIds;
        this.questionAnswers = response.data.questionAnswers
        this.answers = this.reload.answerMap;
        this.selectQuestion(0)
        this.loading = false;
      }else{
        this.bank = response.data;
        this.reload = response.reload;
        this.questionList = response.reload.questionIds;
        if (this.reload.status != '1'){//测试中
          this.questionAnswers = this.reload.questionAnswers
          this.answers = this.reload.answerMap;
        }else{
          this.getAnswers();
          //保存答案定时器
          this.timer = setInterval(() => {
            this.saveAnswers();
          }, 5000)
        }
        this.selectQuestion(0)
        this.loading = false;
      }
    },
    /** 查询题目+保存已回答 */
    selectQuestion(index){
      //查询单个题目
      getQuestion(this.questionList[index]).then(response => {
        this.question = response.data;
        if (this.reload.status == '1' && this.answers[response.data.id] == null){
          this.answers[response.data.id] = response.data.type == '0' ? '' : [];
        }
        this.page.index = index;
        this.page.next = index + 1;
        this.page.previous = index - 1;
        this.page.doCount = index + 1;
      });
    },
    /** 保存答案 */
    saveAnswers(){
      save_answers(this.bankId,this.answers).then( response =>{
        this.saveCount++;
        if (this.saveCount % 4 === 0){
          this.$notify.success({title: '保存答案成功 '+this.saveCount +'次', message: parseTime(new Date())});
        }
      });
    },
    /** 获取答案 */
    getAnswers(){
      get_answers(this.bankId).then( response =>{
        if (isNotEmpty(response.data)){
          if (this.reload.status == '1'){//测试中
            //生成答案对象
            this.answers = response.data;
            this.questionList.forEach( item => {
              if (this.answers[item] == undefined){
                this.answers[item] = null;
              }
            })
          }
        }
      })
    },
    /** 交卷 */
    submit(){
      this.$confirm('交卷后将无法修改，您确定要交卷吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (this.timer){
          clearInterval(this.timer)
        }
        const loading = this.$loading({
          lock: true,
          text: '后台审核中，请稍后',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        this.reload['answerMap'] = this.answers;
        this.reload['status'] = 3;
        updateEx_study_reload(this.reload).then(({data}) => {
          this.$modal.msgSuccess("交卷成功");
          this.applyBank();
          loading.close();
        });
      }).catch(() => {
        this.$modal.msg("未交卷，请认真检查");
      });
    }
  },
  beforeDestroy() {
    clearInterval(this.timer)
  },
  watch:{

  }
};
</script>
<style>
.my_span{
  margin-left: 15px;
}
.my_tag_title , .my_question_title{
  width: 100%;
  font-size: 13px;
  line-height: 55px;
  background: white;
}
.my_tag_title{
  height: 70px;
}
.my_question_title{
  height: auto;
  padding-left: 20px;
}
.my_space_title{
  width: 100%;
  height: 55px;
  font-size: 15px;
  line-height: 55px;
}
</style>
